package xyz.ibenben.zhongdian.common.intercepter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
public class AddPrincipalToSessionFilter extends OncePerRequestFilter {
	/**
	 * 过滤
	 * @param servletRequest 参数
	 * @param servletResponse 参数
	 * @param filterChain 参数
	 * @throws ServletException 异常
	 * @throws IOException 异常
	 */
	@Override
	protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
		Subject currentUser = SecurityUtils.getSubject();
		//判断用户是通过记住我功能自动登录,此时session失效
		if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
				SysUser user= (SysUser) currentUser.getPrincipal();
				//对密码进行加密后验证
//				UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUsername(), sysUser.getPassword(), currentUser.isRemembered())
				//把当前用户放入session
//				currentUser.login(token)
				Session session = currentUser.getSession();
				session.setAttribute(Constants.SESSION, user);
				session.setAttribute(Constants.SESSIONID, user.getId());
				//设置会话的过期时间--ms,默认是30分钟，设置负数表示永不过期
				//session.setTimeout(-1000l)
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
}
